﻿using LuShanTea.IService;
using LuShanTea.Service.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LuShanTea.Service
{
    public class CartService : ICartService
    {
        public long AddNew(long userId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Cart> bs = new BaseService<Cart>(ctx);
                var en = bs.GetAll().SingleOrDefault(e => e.UserId == userId);
                if (en == null)
                {
                    Cart cart = new Cart();
                    cart.UserId = userId;
                    ctx.Carts.Add(cart);
                    ctx.SaveChanges();
                    return cart.Id;
                }
                else
                {
                    en.IsDeleted = false;
                    ctx.SaveChanges();
                    return en.Id;
                }
            }
        }


        /// <summary>
        /// 根据用户Id获取购物车Id
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public long GetCartIdByUserId(long userId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<User> bs = new BaseService<User>(ctx);

                var user = bs.GetAll().SingleOrDefault(u => u.Id == userId);

                if (user == null)
                {
                    throw new ArgumentException("用户Id为：" + userId + "不存在");
                }

                BaseService<Cart> cartBs = new BaseService<Cart>(ctx);

                Cart cart = cartBs.GetAll().SingleOrDefault(c => c.UserId == userId);

                if (cart == null)
                {
                    throw new ArgumentException("用户Id为：" + userId + "的购物车不存在");
                }

                return cart.Id;

            }
        }
    }
}
